/**
 * 日志管理路由
 *
 * Created by snowingsea on 2020/02/24.
 */
const middleware = require('./../middleware');
const PhoenixError = require('./../../models/phoenix-error');
const logs = require('./../../models/logs');

/**
 * 获取错误日志
 * @param req
 * @param res
 * @param next
 */
function getErrorLogs(req, res, next) {
  const result = {};
  const startTime = (req.query.startTime && parseInt(req.query.startTime, 10)) || null;
  const endTime = (req.query.endTime && parseInt(req.query.endTime, 10)) || null;

  result.pagination = req.filter || {};
  logs.getErrorLogs({
    ...result.pagination,
    startTime,
    endTime,
  })
    .then((errorLogs) => {
      result.logs = errorLogs.map((errorLog) => logs.getErrorLogJson(errorLog));
      return logs.getErrorLogsTotal({
        q: result.pagination.q,
        startTime,
        endTime,
      });
    })
    .then((count) => {
      result.pagination.total = count;
      res.json(result);
    })
    .catch((err) => {
      next(new PhoenixError(err));
    });
}

/**
 * Export model definition object.
 */
module.exports = (app, prefix) => {
  const errorLogsURL = `${prefix}/error-logs.json`;

  // 获取错误日志
  app.get(errorLogsURL, middleware.user.requireTokenUnexpired);
  app.get(errorLogsURL, middleware.user.requireAvailable);
  app.get(errorLogsURL, middleware.user.requireAdministrator);
  app.get(errorLogsURL, middleware.splitFilter);
  app.get(errorLogsURL, getErrorLogs);
};
